<template>
   <div>
      <div class="flex flex-wrap gap-4">
         <template v-for="(item, index) in cardData" :key="index">
            <el-card
               style="width: 380px"
               shadow="hover"
               @click="getfetchMarkdown(item, index)"
               :class="[setCardBg(index)]"
            >
               {{ item.name }}
            </el-card>
         </template>
      </div>

      <MdEditor style="text-align: left" v-model="mdText"></MdEditor>
   </div>
</template>
<script setup lang="ts">
import { ref, toRef, reactive, onMounted, computed, nextTick } from 'vue';
import { MdEditor } from 'md-editor-v3';
import { fetchMarkdown } from '@/utils/fetchMarkdown';
import 'md-editor-v3/lib/style.css';

const mdText = ref('');
const activeIdx = ref(0);
// const activeIdx = toRef(count);

const cardData = reactive([
   { id: 1, name: 'this指针、闭包、作用域', url: '/src/views/jsModule/this指针、闭包、作用域.md' },
   {
      id: 2,
      name: '面向对象编程、原型及原型链',
      url: '/src/views/jsModule/面向对象编程、原型及原型链.md',
   },
   { id: 3, name: 'promise 规范及应用', url: '/src/views/jsModule/promise规范及应用.md' },
   { id: 4, name: 'JS模块化详解', url: '/src/views/jsModule/JS模块化详解.md' },
   {
      id: 5,
      name: '浏览器内置 JS 对象详解 & 浏览器事件模型详解 & 浏览器请求相关内容详解',
      url: '/src/views/jsModule/浏览器内置 JS 对象详解 & 浏览器事件模型详解 & 浏览器请求相关内容详解.md',
   },
   { id: 6, name: 'JS性能优化', url: '/src/views/jsModule/JS性能优化.md' },
   { id: 7, name: 'JS函数式编程', url: '/src/views/jsModule/函数式编程.md' },
]);

const setCardBg = computed(() => (val) => {
   console.log(activeIdx.value);

   return activeIdx.value === val ? 'active-bg' : '';
});

function getfetchMarkdown(val, idx) {
   let url = val ? val.url : cardData[0].url;
   if (idx != undefined) activeIdx.value = idx;
   if (val) url = val.url;
   fetchMarkdown(url).then((res) => {
      mdText.value = res;
   });
}

onMounted(() => {
   getfetchMarkdown();
});
</script>

<style lang="scss" scoped>
.active-bg {
   background-color: #409eff;
   color: #fff;
}
</style>
